package com.ty.job;

import com.ty.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Quartz Job
 *
 * @Author Tommy
 * @Date 2023/10/22
 */
@DisallowConcurrentExecution
@Slf4j
public class MyJob implements Job {

    private static int tick = 0;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        tick++;

        ThreadLocal<Integer> n = new ThreadLocal<>();
        n.set(tick);

        log.info("第{}次：开始执行Quartz Job...", n.get());
        System.out.println(jobExecutionContext);
        System.out.println(scheduler);

        // 用于测试：DisallowConcurrentExecution
        // 模拟业务逻辑处理时间过长，已经超过了2个调度周期
        // MisFire机制：当本逻辑处理完毕后，总会再执行一次（无论超出几个周期，只执行1次）
        if (n.get() == 2) {
            ThreadUtil.sleep(10, "#" + n.get());
        }

        // 模拟重试机制
        try {
            if (n.get() == 3) {
                System.out.println(1 / 0);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.info("{} 重试...", "#" + n.get());

            ThreadUtil.sleep(1, "#" + n.get());
            throw new JobExecutionException(true);
        }

        log.info("第{}次 Quartz Job执行结束", n.get());
    }
}
